import os

all_files = {os.path.join(root,file) for root,dirs,files in os.walk("./exec_binary") for file in files}

binaries = []
for file in all_files:
    if file + ".bios.bin" in all_files:
        binaries.append(file)
binaries = sorted(binaries)

keys = []
vals = {}
with open('config.sim','rt') as f:
    lines = f.readlines()
    for line in lines:
        line = line.strip()
        if line == '':
            continue
        parts = line.split("=")
        key = parts[0]
        assert key not in keys
        keys.append(key)
        vals[key] = '='.join(parts[1:])

def select(hint):
    if hint.isnumeric():
        index = int(hint)
        name = binaries[index]
    elif hint in binaries:
        name = hint
    else:
        raise RuntimeError('Cannot find binary "%s"' % hint)
    vals['bios'] = '%s.bios.bin' % name
    vals['kernel'] = name

def save():
    config = ['%s=%s' % (key,vals[key]) for key in keys]
    text = '\n'.join(config)
    print(text)
    with open('config.sim','wt') as f:
        print(text,file=f)


def displayList():
    print("There are %d binaries to select:" % len(binaries))
    for i in range(len(binaries)):
      print('[%d] %s' % (i,binaries[i]))

if __name__ == "__main__":
    displayList() 
    select(input("Please select binary to run:"))
    save()
